package Example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 可以控制某个资源被同时访问的个数
 * <p>
 * 使用场景：比如数据库的连接池，可以通过Semaphore来控制最大的访问个数
 *
 * @author Wang Renlei
 * @Date 2020/7/9
 */
@Slf4j
public class SemaphoreExample2 {

    private static int threadCount = 20;

    public static void main(String[] args) throws InterruptedException {

        ExecutorService executorService = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(5);

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            executorService.execute(() -> {
                try {
                    //尝试获取许可
                    if (semaphore.tryAcquire()) {
                        //业务逻辑
                        test(threadNum);
                        //释放一个许可
                        semaphore.release();
                    }

                } catch (InterruptedException e) {
                    log.error("exception", e);
                } finally {
                }
            });
        }
        log.info("finish");
        executorService.shutdown();
    }

    private static void test(int threadNum) throws InterruptedException {
        log.info("{}", threadNum);
        Thread.sleep(1000);
    }
}
